package com.itany.shop.servlet;

import com.itany.shop.entity.Product;
import com.itany.shop.factory.ObjectFactory;
import com.itany.shop.service.ProductService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

/**
 * @author 黄衡熙
 * @version 1.0
 */
@WebServlet("*.product")
public class ProductServlet extends HttpServlet {
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        req.setCharacterEncoding("utf-8");
//        resp.setContentType("text/html;charset=utf-8");
        String path = req.getServletPath();
        switch (path) {
            case "/findAll.product":
                findAll(req, resp);
                break;
            default:
                PrintWriter out = resp.getWriter();
                out.println("<h1 style='color:red;'>对不起,您访问的资源有误,请检查请求是否正确</h1>");
        }
    }

    protected void findAll(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ProductService productService = (ProductService) ObjectFactory.getObject("productService");
        // 查询
        List<Product> products = productService.findAll();
        req.setAttribute("products",products);
        req.getRequestDispatcher("/jsp/main.jsp").forward(req,resp);
    }
}
